package net.hualisheng.netty.service;

import net.hualisheng.netty.process.MultiProcess;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

public class MultiReactor {
    public  void main(String[] args) throws IOException {
        Selector selector = Selector.open();
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.configureBlocking(false);

        ssc.bind(new InetSocketAddress(8099));
        ssc.register(selector, SelectionKey.OP_ACCEPT);

        int coreNum = Runtime.getRuntime().availableProcessors();
        MultiProcess[] processors = new MultiProcess[coreNum];
        for (int i = 0; i <processors.length ; i++) {
            processors[i]=new MultiProcess();
        }

        int index = 0;
        while (selector.select() > 0) {
            Set<SelectionKey> keySet = selector.selectedKeys();
            Iterator<SelectionKey> iterator = keySet.iterator();
            while (iterator.hasNext()) {
                SelectionKey selectionKey = iterator.next();
                iterator.remove();
                if (selectionKey.isAcceptable()) {
                    ServerSocketChannel accept = (ServerSocketChannel) selectionKey.channel();
                    SocketChannel soc = accept.accept();
                    soc.configureBlocking(false);
                    MultiProcess processor = processors[(index++) % coreNum];

                    processor.addChannel(soc);
                    processor.wakeUp();
                }
            }
        }

    }
}
